#!/bin/sh
function file_exists(){
    while [ true ]
    do
        if [ -f $1 ]; then
            return
        fi
        echo "请在 app 文件夹中放入需要运行的 $1 文件。"
        sleep 5
    done
}

function find_py(){
    while [ true ]
    do
        first_py=$(find /app -type f -name "*.py" | head -n 1)
        if [ ! -z "$first_py" ]; then
            echo "正在运行 $first_py"
            python3 -u $first_py
            return
        fi
        echo "请在 app 文件夹中放入需要运行的 .py 文件。"
        sleep 5
    done
}

if [ "$1" = "sh" ]; then
    exec "sh"
else
    if [ ! -f /etc/python.sit ]; then
        sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
        sed -i 's/#http/http/g' /etc/apk/repositories
        apk update && apk upgrade
        apk --no-cache add tzdata
        ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
        echo "Asia/Shanghai" > /etc/timezone
        pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
        pip install --upgrade pip
 
        APK_ADD=${APK_ADD:-""}
        if [ "$APK_ADD" != "" ]; then
            echo "apk add $APK_ADD"
            apk add $APK_ADD
        fi

        PIP_INSTALL=${PIP_INSTALL:-""}
        if [ "$PIP_INSTALL" != "" ]; then
            echo "pip install $PIP_INSTALL"
            pip install $PIP_INSTALL
        fi

        echo "python3" > /etc/python.sit
    fi

    PY_FILE=${PY_FILE:-""}
    if [ "$PY_FILE" != "" ]; then
        file_exists $PY_FILE
        echo "正在运行 $PY_FILE"
        python3 -u $PY_FILE
    else
        find_py
    fi

    while [ true ]
    do
        echo "程序已经运行结束，请关闭或重启容器。"
        sleep 3600
    done

fi
